const db = require("../models/index");
const goods = db.sequelize.import("../models/goods");
const goodsSeries = db.sequelize.import("../models/goods_series");
const goodsImg = db.sequelize.import("../models/goods_img");
const goodsDesc = db.sequelize.import("../models/goodsdesc");
const md5 = require('md5-node');
const {Op} = require('sequelize');
function arrayGroup(arrs){
    return arrs.reduce((a, b) => {
        const arr = [];
        a.forEach(i => {
            b.forEach(j => {
                arr.push(i + "_" + j);
            });
        });
        return arr;
    });
}
module.exports={
    list: async function(req,res,next){
        //当前页数
        let pageNo = req.body.pageNo;
        //每页记录数
        let limit = req.body.pageSize;
        //当前页之前的所有记录
        let offset = (pageNo-1)*limit;
        let goodsName = req.body.goodsName;
        let data = await goods.findAndCountAll({
            where:{goods_name:{[Op.like]:'%'+goodsName+'%'}},
            order:[['id','DESC']],//asc从小到大，desc从大到小
            offset,//当前页之前的所有记录
            limit,//每页记录数
            raw:false
        });
        data = JSON.parse(JSON.stringify(data));
        console.log(data);
        res.json({"code":200,"data":data,"msg":"查询用户列表成功"});
        return false;
    },
    add: function(req,res,next){
        console.log(req.body);
        let dynamicParam = req.body.dynamicParam?req.body.dynamicParam:[];
        let staticAttr = req.body.staticAttr?req.body.staticAttr:[];
        let pics = req.body.pics?req.body.pics:[];
        let goodsSeriesId = req.body.series_id;
        let goods_desc = req.body.goods_desc;
        let goods_name = req.body.goods_name;
        let goods_price = req.body.goods_price;
        let goods_weight = req.body.goods_weight;
        let goods_number = req.body.goods_number;
        let goods_cate = req.body.goods_cate;
        let arrs=[];
        let transaction=null;
        let addGoodsResult=null;
        if(dynamicParam.length>1){
            for (let i = 0; i < dynamicParam.length; i++) {
                let attrValue = dynamicParam[i].attr_value;
                attrValueArr = attrValue.split("_");
                arrs.push(attrValueArr);
            }
            
            console.log(arrayGroup(arrs));
            (async ()=>{
                transaction = await db.sequelize.transaction();
                
                try {
                    
                    if(goodsSeriesId){
                        let goodsSeriesData={
                            dparam_values:JSON.stringify(dynamicParam),
                            sattr_values:JSON.stringify(staticAttr)
                        };
                        //更新商品系列表
                        await goodsSeries.update(goodsSeriesData,{where:{id:goodsSeriesId},transaction});
                    }
                    //图片先按系列id插入，如果以后前台查询到商品本身没有图片，可以使用系列的图片作为默认图片显示
                    if(pics.length>0){
                        let picData = [];
                        for(let i =0;i<pics.length;i++){
                            let picObj={
                                mid_img:pics[i].path,
                                series_id:goodsSeriesId,
                                create_stamp:new Date().getTime(),
                                update_stamp:new Date().getTime()
                            }
                            picData.push(picObj);
                        }
                        await goodsImg.bulkCreate(picData,{transaction});
                    }
                    //商品详情默认与系列id关联，如果查询商品本身没有关联详情，可以使用默认的系列详情
                    if(goods_desc){
                        await goodsDesc.create({
                            series_id:goodsSeriesId,
                            goods_desc:goods_desc,
                            create_stamp:new Date().getTime(),
                            update_stamp:new Date().getTime()
                        },{transaction});
                    }
                    //组合商品属性
                    let attrs = arrayGroup(arrs);
                  
                    let goodsData=[];
                    let cateArr = goods_cate.split("_");
                    for(let i=0;i<attrs.length;i++){
                        //使用系列id和属性组合通过md5形成一个唯一的标识
                        //方便移动端详情页选中属性组合时进行查询
                        let series_flag = md5(encodeURIComponent(goodsSeriesId+attrs[i]));
                        let attrArr = attrs[i].split("_");
                        let tmpGoodsName = goods_name;
                        //在商品名称后面加上属性组合
                        for(let j=0;j<attrArr.length;j++){
                            tmpGoodsName+=" "+attrArr[j];
                        }
                        let goodsObj={
                            goods_name:tmpGoodsName,
                            goods_price,
                            goods_weight,
                            goods_number,
                            series_flag,
                            cat_one_id:cateArr[0],
                            cat_two_id:cateArr[1],
                            cat_three_id:cateArr[2],
                            create_stamp:new Date().getTime(),
                            update_stamp:new Date().getTime()
                        }
                        goodsData.push(goodsObj);
                    }
                    //添加商品表记录
                    addGoodsResult = await goods.bulkCreate(goodsData,{transaction});
                    
                    await transaction.commit();
                } catch (error) {
                    console.log(error);
                    await transaction.rollback();
                    res.json({"code":500,"data":null,"msg":"添加失败,"+error});
                }

            })();
        }
        
        //执行成功，返回新的数据对象，如果只需要id的话，可以addResult.id
        res.json({"code":200,"data":addGoodsResult,"msg":"添加成功"});
        return false;
    },
    findById: async function(req,res,next){
        let paramId = req.body.id;
        //返回的是对象数组，里面只有一个对象
        let data = await goods.findAll({where:{id:paramId}});
        res.json({"code":200,"data":data,"msg":"查询用户成功"});
        return false;
    },
    upd: async function(req,res,next){
        
        //返回的是受影响的行数，如:[1]
        let data = await goods.update(req.body,{where:{id:req.body.id}});
        res.json({"code":200,"data":data,"msg":"修改用户成功"});
        return false;
    },
    del: async function(req,res,next){
        let data = await goods.destroy({where:{id:req.body.id}});
        res.json({"code":200,"data":data,"msg":"删除用户成功"});
        return false;
    }
}